import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getStorageItem } from '@/utils/auth'
import baseURL from './env.js'

// 白名单
const whiteUrl = ['/login']

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // 白名单
    // const url = config.url.replace(config.baseURL, '')
    // if (whiteUrl.some(wl => wl === url)) {
    //   return config
    // }
    // config.headers['token'] = 'token'
    // return config
    // do something before request is sent
    if (store.getters.token) {
      // config.headers['Authorization'] = `Authorization ${getStorageItem()}`
      config.headers.Authorization = `${getStorageItem('token')}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    const { msg, status } = res.meta
    const errMsg = msg || '请求失败'
    if (status === 200 || status === 201 || status === 204) {
      if (response.config.method !== 'get') {
        Message({
          message: errMsg,
          type: 'success',
          duration: 3 * 1000
        })
      }
      return res
    } else {
      if (status === 401) {
        MessageBox.confirm('Token已失效，是否重新登录', '确认退出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      } else if (status === 422) {
        Message({
          message: '创建失败',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        Message({
          message: errMsg,
          type: 'error',
          duration: 3 * 1000
        })
      }
      return Promise.reject(new Error(errMsg))
    }
  },
  error => {
    const { msg } = error.response.data
    Message({
      message: msg || '请求失败',
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
